package com.htu.courseService.common.util;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * Created By JNNarrator on 2024/9/7 17:07
 * email: jiangn09@chinatelecom.cn
 */
public class SymmetricCryptoUtil {
	/**
	 * 16字节
	 */
	private static final String ENCODE_KEY = "1234567812345678";
	private static final String IV_KEY = "0000000000000000";
	
	public static String encode(String decode)
	{
		return encryptFromString(decode, Mode.CBC, Padding.ZeroPadding);
	}
	public static String decode(String encode)
	{
		return decryptFromString(encode, Mode.CBC, Padding.ZeroPadding);
	}
	
	public static String encryptFromString(String data, Mode mode, Padding padding) {
		AES aes;
		if (Mode.CBC == mode) {
			aes = new AES(mode, padding,
					new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
					new IvParameterSpec(IV_KEY.getBytes()));
		} else {
			aes = new AES(mode, padding,
					new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
		}
		return aes.encryptBase64(data, StandardCharsets.UTF_8);
	}
	
	public static String decryptFromString(String data, Mode mode, Padding padding) {
		AES aes;
		if (Mode.CBC == mode) {
			aes = new AES(mode, padding,
					new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
					new IvParameterSpec(IV_KEY.getBytes()));
		} else {
			aes = new AES(mode, padding,
					new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
		}
		byte[] decryptDataBase64 = aes.decrypt(data);
		return new String(decryptDataBase64, StandardCharsets.UTF_8);
	}
	
}


